
import {RequestConfig,request} from '../config';

import {store} from "../store";
import {ref} from "vue";
import { login } from '../api/user';

const createKey = (path: string, data: any) => `${JSON.stringify(data)}${path}`

//储存request请求map
const requestList: Map<string, UniApp.RequestTask> = new Map()

//是否正在加载中
let loadingBox: null | (() => null) = null

/**
 * request请求
 * @param param0 必要参数
 * @param param1 配置
 */

export const base_ip = ref('')

const RequestMethod: request = (
    { methodType = 'GET', data = {}, url = '' },
    { header = {Authorization:''}, loading = true, dataType = 'json' } = {}
) => {
    return new Promise((resolve, reject) => {
        //生成key
        const requestKey = createKey(url, data)

        // 加载动画
        let token = store.getters.token

        if (token != ''){
            header.Authorization = 'Bearer ' + token
        }
        const requestClose = uni.request({
            /** 服务器接口地址 */
            url: `http://${base_ip.value}:8080${url}`,
            /** 请求的参数 */
            data: data,
            /** 请求头 */
            header: header,
            /** 请求类型 */
            method: methodType,
            /** 超时时间 */
            timeout: 30000,
            /** 返回数据类型 */
            dataType: dataType,
            // 成功
            success: res => {
                // @ts-ignore
                if (res.data.code == 200){
                    //返回数据
                    resolve({
                        code:200,
                        data:res.data as any
                    })
                }
                // @ts-ignore
                if (res.data.code == 401){
                    uni.showToast({
                        title:'登录过期,请重新登录',
                        icon:'error',
                        duration:1000,
                        success:()=>{
                            uni.setStorage({
                                key:'token',
                                data:''
                            })
                            store.dispatch('SET_TOKEN','')
                            uni.reLaunch({
                                url:'/pages/login/index'
                            })
                        }
                    })
                }
            },
            // 失败
            fail: err => {
                reject(err)
            },
            // 最终执行
            complete: () => {
                // 移除request请求
                requestList.delete(requestKey)
                // 如果加载
                if (loadingBox !== null && requestList.size === 0) {
                    // 关闭提示
                    loadingBox = loadingBox()
                }
            },
        })
        //先关闭上一个同路径同参数请求
        requestList.get(requestKey)?.abort()
        //存储请求
        requestList.set(requestKey, requestClose)
    })
}

//get请求
export const get = <R = AnyObject, T = AnyObject>(
    url: string,
    data?: T,
    config?: RequestConfig,
) =>
    RequestMethod<R, T>(
        {
            methodType: 'GET',
            url: url,
            data,
        },
        config,
    )

//post请求
export const post = <R = AnyObject, T = AnyObject>(
    url: string,
    data?: T,
    config?: RequestConfig,
) =>
    RequestMethod<R, T>(
        {
            methodType: 'POST',
            url: url,
            data,
        },
        config
    )
